package com.ruoyi.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.app.domain.AppApply;
import com.ruoyi.app.domain.bo.AppApplyBo;
import com.ruoyi.app.domain.vo.AppApplyVo;
import com.ruoyi.app.domain.vo.AppAssetVo;
import com.ruoyi.app.mapper.AppApplyMapper;
import com.ruoyi.app.service.IAppApplyService;
import com.ruoyi.app.service.IAppAssetService;
import com.ruoyi.app.service.IAppDetailService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BillType;
import com.ruoyi.common.enums.CoinType;
import com.ruoyi.common.enums.DetailEnums;
import com.ruoyi.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * APP用户提现申请Service业务层处理
 *
 * @author heise
 * @date 2025-12-20
 */
@RequiredArgsConstructor
@Service
public class AppApplyServiceImpl implements IAppApplyService {

    private final AppApplyMapper baseMapper;
    private final IAppAssetService appAssetService;
    private final IAppDetailService appDetailService;

    /**
     * 查询APP用户提现申请
     */
    @Override
    public AppApplyVo queryById(Long applyId) {
        return baseMapper.selectVoById(applyId);
    }

    /**
     * 查询APP用户提现申请列表
     */
    @Override
    public TableDataInfo<AppApplyVo> queryPageList(AppApplyBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppApply> lqw = buildQueryWrapper(bo);
        Page<AppApplyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询APP用户提现申请列表
     */
    @Override
    public List<AppApplyVo> queryList(AppApplyBo bo) {
        LambdaQueryWrapper<AppApply> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AppApply> buildQueryWrapper(AppApplyBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppApply> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getApplyId() != null, AppApply::getApplyId, bo.getApplyId());
        lqw.eq(bo.getUserId() != null, AppApply::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getApplyType()), AppApply::getApplyType, bo.getApplyType());
        lqw.like(StringUtils.isNotBlank(bo.getBankName()), AppApply::getBankName, bo.getBankName());
        lqw.eq(StringUtils.isNotBlank(bo.getBankCode()), AppApply::getBankCode, bo.getBankCode());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), AppApply::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增APP用户提现申请
     */
    @Override
    public Boolean insertByBo(AppApplyBo bo) {
        AppApply add = BeanUtil.toBean(bo, AppApply.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setApplyId(add.getApplyId());
        }
        return flag;
    }

    /**
     * 修改APP用户提现申请
     */
    @Override
    public Boolean updateByBo(AppApplyBo bo) {
        AppApply update = BeanUtil.toBean(bo, AppApply.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean passOrder(AppApplyBo bo) {
        if (updateByBo(bo)) {
            AppApplyVo appApplyVo = queryById(bo.getApplyId());
            if (bo.getStatus().equals(Constants.TWO)) {
                appAssetService.addBalance(appApplyVo.getUserId(), appApplyVo.getBalance());
                appDetailService.insert(appApplyVo.getUserId(), appApplyVo.getBalance(), BigDecimal.ZERO, BillType.IN.getCode(), CoinType.GOLD.getCode(), DetailEnums.TO.getCode(), "提现驳回", null);
            } else {
                //转账
            }
            return true;
        }
        return false;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppApply entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除APP用户提现申请
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean applyBalance(AppApplyBo bo) {
        if (appAssetService.subtractBalance(bo.getUserId(), bo.getBalance()) && insertByBo(bo)) {
            appDetailService.insert(bo.getUserId(), bo.getBalance(), BigDecimal.ZERO, BillType.TO.getCode(), CoinType.GOLD.getCode(), DetailEnums.TO.getCode(), "申请提现", null);
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean integralExchange(AppAssetVo appAssetVo, BigDecimal integral, BigDecimal balance) {
        Boolean result = appAssetService.subtractIntegral(appAssetVo.getUserId(), integral);
        if (result) {
            appDetailService.insert(appAssetVo.getUserId(), integral, BigDecimal.ZERO, BillType.TO.getCode(), CoinType.INTE.getCode(), DetailEnums.CHANGE.getCode(), "积分兑换贡献度-扣除", null);
            appAssetService.addContribution(appAssetVo.getUserId(), balance);
            appDetailService.insert(appAssetVo.getUserId(), balance, BigDecimal.ZERO, BillType.IN.getCode(), CoinType.CONTRIBUTION.getCode(), DetailEnums.CHANGE.getCode(), "积分兑换贡献度-增加", null);
        }
        return result;
    }
}
